<template>
	<view class="window-top">
		<view class="window-flex">
			<view v-show="currentTabbar === 0" class="window-box">
				<scroll-view class="window-scroll" :scroll-y="false" @scrolltolower="tabbarPageScrollLower">
					<mallt ref="mallt" :bg="BgMallt" :banner="banner" :posTop="topPlace" @nerTop="backNerTop"
						@navBanner="navBanner" @navUserEvent="swtouser(4)">
					</mallt>
				</scroll-view>
			</view>

			<view v-show="currentTabbar === 1" class="window-box">
				<scroll-view class="window-scroll" scroll-y @scrolltolower="tabbarPageScrollLower">
					<cart ref="cart" :bg="BgCart" @nerTop="backNerTop"></cart>
				</scroll-view>
			</view>

			<view v-show="currentTabbar === 2" class="window-box">
				<scroll-view class="window-scroll" scroll-y :scroll-top="scrollPoint"
					@scrolltolower="tabbarPageScrollLower">
					<home ref="home" @nerTop="backNerTop"></home>
				</scroll-view>
			</view>

			<view v-show="currentTabbar === 3" class="window-box">
				<scroll-view class="window-scroll" scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
					<ring ref="ring" :banner="banner" :msgChange="msgChange"></ring>
				</scroll-view>
			</view>

			<view v-show="currentTabbar === 4" class="window-box">
				<scroll-view class="window-scroll" :scroll-y="false" enable-back-to-top
					@scrolltolower="tabbarPageScrollLower">
					<person ref="person"></person>
					<view style="height: 100px;"></view>
				</scroll-view>
			</view>

			<tn-tabbar v-model="currentTabbar" fixed switch-animation @change="switchTabbar" height="50px">
				<!--
				<tn-tabbar-item v-for="(item, index) in tabbarData" :key="index" :icon="item.icon"
					:active-icon="item.activeIcon" :text="item.name" active-color="#000"
					:bulge="index === 2"></tn-tabbar-item>
				-->
				<tn-tabbar-item icon="shop" active-icon="shop-fill" text="悦玺云商" active-color="#000"></tn-tabbar-item>
				<tn-tabbar-item icon="menu-classify" active-icon="menu-classify-fill" text="分类"
					active-color="#000"></tn-tabbar-item>
				<tn-tabbar-item icon="home-smile" active-icon="home-smile-fill" text="新品" active-color="#000"
					bulge></tn-tabbar-item>
				<tn-tabbar-item icon="email" active-icon="email-fill" text="消息" active-color="#000"
					:badge="msgCount"></tn-tabbar-item>
				<tn-tabbar-item icon="identity" active-icon="identity-fill" text="个人中心"
					active-color="#000"></tn-tabbar-item>
			</tn-tabbar>
		</view>
	</view>

	<!-- popup 弹窗-->
	<tn-popup v-model="showBind" radius="0" bg-color="transparent">
		<view class="tn-gradient-bg__cool-5 top-font-title"
			style="border-radius: 60px 0 60px 0;padding: 20px;color: #fff;display: flex;flex-direction: column;align-items: center;gap: 10px;">
			<view style="font-size: large;">悦玺云商</view>
			<view style="font-size: large;"> 您尚未收到会员邀请。请扫描会员邀请码加入商城。 </view>
			<!-- button plain style="margin-top: 20px;">加入会员</button -->
		</view>
	</tn-popup>
	<tn-popup v-model="showLevel" radius="0" bg-color="transparent">
		<view class="tn-gradient-bg__cool-5 top-font-title"
			style="border-radius: 60px 0 60px 0;padding: 20px;color: #fff;display: flex;flex-direction: column;align-items: center;gap: 10px;">
			<view style="font-size: large;">VIP会员权益</view>
			<view style="font-size: large;">指定商品二选一</view>
			<view style="font-size: large;">赠送VIP专属代金券，价值200元</view>
			<view style="font-size: large;">邀约VIP会员，享10%返佣</view>
			<button plain style="margin-top: 20px; color: #fff;" @tap="EventNavVip">升级VIP</button>
		</view>
	</tn-popup>
	<tn-popup v-model="showPhone" radius="0" bg-color="transparent">
		<view class="tn-gradient-bg__cool-5 top-font-title"
			style="border-radius: 60px 0 60px 0;padding: 20px;color: #fff;display: flex;flex-direction: column;align-items: center;gap: 10px;">
			<view style="font-size: large;">手机认证</view>
			<view style="font-size: large;">完成手机认证享签到积分。 </view>
			<button plain style="margin-top: 20px;">立即认证</button>
		</view>
	</tn-popup>

	<personVerifyPopVue ref="personVerifyPop"></personVerifyPopVue>
</template>

<script>
	import utils from '@/common/utils.js'
	import QQMapWX from '@/common/qqmap-wx-jssdk.js'
	import personVerifyPopVue from '@/components/person-verify-pop/person-verify-pop.vue';
	import psMethod from '@/common/psMethod';
	export default {
		data() {
			return {
				topH: 0,
				title: 'index',
				sConf: getApp().globalData,
				currentTabbar: 2,
				// 推荐链接
				staff: null,
				curStaff: null,
				// 其他参数
				scrollPoint: 100,
				scrollPointOne: 100,
				scrollPointTow: 100,
				// 自定义底栏对应页面的加载情况
				tabberPageLoadFlag: [],
				tabbarData: [{
						name: '悦玺商城',
						icon: 'shop',
						activeIcon: 'shop-fill',
					},
					{
						name: '分类',
						icon: 'menu-classify',
						activeIcon: 'menu-classify-fill',
					},
					{
						name: '首页',
						icon: 'home-smile',
						activeIcon: 'home-smile-fill',
					},
					{
						name: '动态',
						icon: 'footprint',
						activeIcon: 'footprint-fill',
					},
					{
						name: '个人中心',
						icon: 'identity',
						activeIcon: 'identity-fill',
					}
				],
				// 组件数据
				BgMallt: null, // 商城头图背景
				BgCart: null, //  分类
				banner: null, // banner	
				link: [], // banner链接			
				showBind: false, // 弹窗绑定会员
				showLevel: false, // 弹窗会员权益	
				showPhone: false, // 绑定手机

				qqmapsdk: null, // 腾讯地图SDK	
				topPlace: [], // 首推商户

				msgCount: 0, // 站内信


			};
		},
		onLoad(args) {
			console.log("onLoad", 'index');
			let staff = Number(args.parent) || null;
			this.staff = staff
			// if (!this.sConf.auth) {
			// 	console.log('未登录');
			// 	this.autoLogin()
			// }
			this.loadDefData()
		},
		onReady() {
			console.log('onReady index');
			this.checkForUpdate()

		},
		onShow() {
			console.log('onShow index');

		},
		methods: {
			async autoLogin() {
				console.log('无用户登录-自动登录');
				let code = await uni.login({
					provider: 'weixin',
					onlyAuthorize: true
				})
				console.log('wxCode->', code.code);
				let login = await this.hasWxCode(code.code).then(res => {
					console.log('登录完成->', res);
					this.curStaff = res.auth
					this.sConf.auth = res.auth
					this.sConf.token = res.token
				})

			},
			hasWxCode(e) {
				let host = this.sConf.host + '/weapps/login/'
				let data = {
					code: e
				}
				return new Promise((resolve, reject) => {
					psMethod.requestPostSync(host, data).then(res => {
						console.log('微信快速登录->', res);
						resolve(res.resmsg)
					}).catch(err => {
						reject(err)
					})
				})
			},
			async loadDefData() {
				// 加载数据
				await utils.httpRequestOnList(this.sConf.host + '/api/conf/', {
					key: 'tt_bg_mallt'
				}).then((res) => {
					console.log('加载头图——页面0');
					this.BgMallt = res.find(item => item.key === 'tt_bg_mallt').value;
				})

				await utils.httpRequestOnList(this.sConf.host + '/api/conf/', {
					key: 'tt_bg_cart'
				}).then((res) => {
					console.log('加载头图——页面1');
					this.BgCart = res.find(item => item.key === 'tt_bg_cart').value;
				})

				await utils.httpRequestOnList(this.sConf.host + '/api/image/', {
					mode: 'swiper',
					cur: 0,
					status: 1,
					ordering: '-sort'
				}).then((res) => {
					console.log('加载轮播——页面0', res);
					let tmpData = []
					let linkData = []
					res.forEach(item => {
						tmpData.push(item.url)
						linkData.push(item.link)
					})
					this.banner = tmpData
					this.link = linkData
				})
				await utils.httpRequestOnList(this.sConf.host + '/weapps/matrix/', {
					ordering: 'sort'
				}).then(res => {
					console.log('加载首推商户->', res);
					this.topPlace = res;
				}).catch(err => {
					console.log('加载首推商户=>', err);
				})

				await utils.httpRequestOnList(this.sConf.host + '/api/mapWx/', this.sConf.token, {}).then(res => {
					console.log('加载腾讯地图api密钥->', res);
					this.qqmapsdk = new QQMapWX({
						key: res
					});
				}).catch(err => {
					console.log('加载腾讯地图api密钥=>', err);
				})



				// let that = this
				// // 加载用户位置
				// if (this.sConf.city === null) {
				// 	uni.getSetting({
				// 		success(res) {
				// 			if (res.authSetting['scope.userLocation']) {
				// 				console.log('已经授权');
				// 				that.MethodUserPoint()
				// 			} else if (res.authSetting['scope.userLocation'] === false) {
				// 				console.log('已经授权__拒绝');
				// 				uni.openSetting({
				// 					success(r) {
				// 						if (r.authSetting['scope.userLocation']) {
				// 							that.MethodUserPoint()
				// 						}
				// 					}
				// 				});
				// 			} else {
				// 				console.log('未授权');
				// 				uni.authorize({
				// 					scope: 'scope.userLocation',
				// 					success(r) {
				// 						console.log('初次授权', r);
				// 						that.MethodUserPoint()
				// 					}
				// 				})
				// 			}
				// 		}
				// 	});
				// }

				this.$refs.home.loadDefData();
			},
			swtouser(e) {
				// #ifdef MP-WEIXIN				
				wx.vibrateShort();
				// #endif
			},
			checkForUpdate() {
				if (!uni.getUpdateManager) return
				console.log('^\n|检测小程序更新---->');
				// 检测是否有更新
				const updatemanager = uni.getUpdateManager()
				updatemanager.onCheckForUpdate(res => {
					if (res && res.hasUpdate) {
						// 发现更新版本
						uni.showLoading({
							title: '小程序更新中'
						})
					}
				})
				// 更新提示
				updatemanager.onUpdateReady(function(res) {
					uni.hideLoading()
					uni.showModal({
						title: '小程序更新',
						content: '新版本已经准备好，是否重启应用？',
						success(r) {
							if (r.confirm) {
								updatemanager.applyUpdate()
							}
						}
					})
				})
				// 更新失败
				updatemanager.onUpdateFailed(res => {
					uni.hideLoading()
					uni.showModal({
						title: '提示',
						content: '小程序更新失败',
						showCancel: false
					})
				})
			},
			/**
			 * 绑定推荐
			 */
			bindParentStaff(e) {
				let host = this.sConf.host + '/weapps/bindHelp/';
				let token = this.sConf.token || ''
				let data = {
					parent: e
				}
				utils.authenticatorOnPost(host, token, data).then(res => {
					console.log('绑定推荐官');
				})
			},
			/**
			 * 站内信回调
			 */
			msgChange(e) {
				console.log('加载消息回调', e);
				this.msgCount = e
			},
			homeScrollEnd() {
				this.scrollPoint += 0.01
			},
			pageScrollLower(e) {
				// console.log('pageScrollLower', e);
			},
			tabbarPageScrollLower(e) {
				console.log('tabbarPageScrollLower');
			},
			navBanner(e) {
				console.log('navBanner', e);
				let url = this.link[e] || null
				if (url) {
					uni.navigateTo({
						url: url
					})
				}
			},
			backNerTop(e) {
				console.log('返回顶部距离', e);
				this.topH = e
				uni.pageScrollTo({
					scrollTop: e,
					duration: 300,
				})
			},
			// 切换导航
			switchTabbar(index) {
				console.log("switchTabbar", index);
				if (index === 0) {
					this.$refs.mallt.loadDefData()
					this.EventBindParent()
					this.EventBuyLevel()
				}
				if (index === 1) {
					this.$refs.cart.loadDefData()
				}
				if (index === 2) {
					this.$refs.home.loadDefData()
				}
				if (index === 3) {
					this.$refs.ring.loadDefData()
				}
				if (index === 4) {
					this.$refs.person.loadDefData()
				}
			},
			/**
			 * 绑定会员
			 */
			EventBindParent() {
				return
				if (!this.curStaff.parent) {
					this.showBind = !this.showBind
				}
			},
			/**
			 * 会员权益
			 */
			EventBuyLevel() {
				return
				if (this.curStaff.curLevel.level === 1) {
					this.showLevel = !this.showLevel
				}
			},
			EventNavVip() {
				uni.navigateTo({
					url: '/pagec/member/level'
				})
			},
			/**
			 * 加载用户地理位置
			 */
			MethodUserPoint() {
				let that = this;
				uni.getLocation({
					type: 'wgs84',
					success(res) {
						// console.log('位置', res);
						that.MethodParseAddress(res)
					},
					fail(err) {
						console.log('加载位置_失败', err);
					}
				})
			},
			/**
			 * 解析地址
			 */
			MethodParseAddress(e) {
				let that = this;
				this.qqmapsdk.reverseGeocoder({
					location: {
						latitude: e.latitude,
						longitude: e.longitude
					},
					success(res) {
						// console.log('城市信息', res.result.ad_info.city);
						that.sConf.city = res.result.ad_info.city;
						uni.setStorage({
							key: "city",
							data: {
								city: {
									province: res.result.ad_info.province,
									city: res.result.ad_info.city,
									district: res.result.ad_info.district
								},
								stamp: Date.parse(new Date())
							}
						})
					},
					fail(err) {
						console.log('城市信息_失败', err);
					}
				});
			}
		}
	}
</script>
<style lang="scss" scoped>
	/* start 全屏适配 */
	.window-top {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		overflow: hidden;
	}

	.window-flex {
		flex: 1;
		overflow: hidden;
	}

	.window-box {
		height: 100%;
		overflow: hidden;
	}

	.window-scroll {
		height: 100%;
		overflow: hidden;
	}

	/* end 全屏适配 */
</style>